package com.tree.backend.interceptor;

import com.tree.backend.utils.UserContext;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 企业ID拦截器
 * 用于从请求头或参数中提取企业ID并设置到UserContext
 * @author tree
 */
@Component
public class EnterpriseIdInterceptor implements HandlerInterceptor {
    
    private static final String ENTERPRISE_ID_HEADER = "X-Enterprise-Id";
    private static final String ENTERPRISE_ID_PARAM = "enterpriseId";
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 首先尝试从请求头获取企业ID
        String enterpriseIdStr = request.getHeader(ENTERPRISE_ID_HEADER);
        
        // 如果请求头中没有，则尝试从请求参数获取
        if (enterpriseIdStr == null || enterpriseIdStr.isEmpty()) {
            enterpriseIdStr = request.getParameter(ENTERPRISE_ID_PARAM);
        }
        
        // 如果获取到了企业ID，则设置到UserContext中
        if (enterpriseIdStr != null && !enterpriseIdStr.isEmpty()) {
            try {
                Long enterpriseId = Long.parseLong(enterpriseIdStr);
                UserContext.setCurrentUserEnterpriseId(enterpriseId);
            } catch (NumberFormatException e) {
                // 如果企业ID格式不正确，可以选择抛出异常或者记录日志
                // 这里简单记录，继续处理请求
                // logger.warn("Invalid enterprise ID format: {}", enterpriseIdStr);
            }
        }
        
        // 继续处理请求
        return true;
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求处理完成后，清除ThreadLocal中的数据，避免内存泄漏
        UserContext.clear();
    }
}